<template>
  <div class="activity-detail-container">
    <el-card>
      <!-- 页面标题 -->
      <template #header>
        <div class="card-header">
          <div class="header-left">
            <el-button icon="ArrowLeft" @click="goBack">返回</el-button>
            <h2 class="page-title">活动详情</h2>
          </div>
          <div class="header-actions">
            <el-button 
              type="primary" 
              @click="showEditDialog = true"
              v-if="userStore.hasPermission(ALL_PERMISSIONS.ACTIVITY_UPDATE)"
            >
              编辑活动
            </el-button>
            <el-button 
              type="success" 
              @click="showAddArtistDialog = true"
              v-if="userStore.hasPermission(ALL_PERMISSIONS.ACTIVITY_UPDATE)"
            >
              添加艺人
            </el-button>
          </div>
        </div>
      </template>

      <!-- 面包屑导航 -->
      <el-breadcrumb separator="/" class="breadcrumb">
        <el-breadcrumb-item :to="{ path: '/activities' }">活动管理</el-breadcrumb-item>
        <el-breadcrumb-item>活动详情</el-breadcrumb-item>
      </el-breadcrumb>

      <!-- 活动基本信息 -->
      <div v-if="activity" class="activity-info-section">
        <el-row :gutter="20">
          <el-col :span="16">
            <div class="activity-main-info">
              <h3 class="activity-name">{{ activity.name }}</h3>
              <p class="activity-description" v-if="activity.description">
                {{ activity.description }}
              </p>
              <div class="activity-meta">
                <el-tag :type="getStatusType(activity.status) as any">
                  {{ getStatusText(activity.status) }}
                </el-tag>
                <span class="meta-item">
                  <strong>开始时间:</strong> {{ formatDateTime(activity.startTime) }}
                </span>
                <span class="meta-item">
                  <strong>结束时间:</strong> {{ formatDateTime(activity.endTime) }}
                </span>
                <span class="meta-item">
                  <strong>最大投票数:</strong> {{ activity.maxVotesPerUser }} 票/人
                </span>
              </div>
              <div class="activity-rules" v-if="activity.rules">
                <h4>活动规则:</h4>
                <p>{{ activity.rules }}</p>
              </div>
            </div>
          </el-col>
          <el-col :span="8">
            <div class="activity-banner" v-if="activity.bannerImage">
              <img :src="activity.bannerImage" :alt="activity.name" />
            </div>
            <div class="activity-stats">
              <div class="stat-item">
                <div class="stat-number">{{ activity._count?.activityArtists || 0 }}</div>
                <div class="stat-label">参与艺人</div>
              </div>
              <div class="stat-item">
                <div class="stat-number">{{ getTotalVotes() }}</div>
                <div class="stat-label">总投票数</div>
              </div>
              <div class="stat-item">
                <div class="stat-number">{{ getTotalVoters() }}</div>
                <div class="stat-label">参与投票人数</div>
              </div>
            </div>
          </el-col>
        </el-row>
      </div>

      <!-- 参与艺人列表 -->
      <div class="artists-section">
        <div class="section-header">
          <h3>参与艺人 ({{ activity?.activityArtists?.length || 0 }})</h3>
          <el-button 
            type="primary" 
            size="small"
            @click="showAddArtistDialog = true"
            v-if="userStore.hasPermission(ALL_PERMISSIONS.ACTIVITY_UPDATE)"
          >
            添加艺人
          </el-button>
        </div>
        
        <div v-if="activity?.activityArtists?.length" class="artists-list">
          <el-table :data="activity.activityArtists" stripe>
            <el-table-column label="排序" width="100">
              <template #default="{ row }">
                <el-input-number 
                  v-model="row.sortOrder" 
                  :min="0" 
                  size="small"
                  controls-position="right"
                  style="width: 80px"
                  @change="updateArtistOrder(row)"
                />
              </template>
            </el-table-column>
            <el-table-column label="艺人信息" min-width="250">
              <template #default="{ row }">
                <div class="artist-info">
                  <el-avatar :size="50" :src="row.artist.avatar" />
                  <div class="artist-details">
                    <div class="artist-name">{{ row.artist.name }}</div>
                    <div class="artist-description" v-if="row.artist.description">
                      {{ row.artist.description }}
                    </div>
                  </div>
                </div>
              </template>
            </el-table-column>
            <el-table-column label="投票统计" width="180">
              <template #default="{ row }">
                <div class="vote-stats">
                  <div class="vote-count">{{ getArtistVoteCount(row.artist.id) }} 票</div>
                  <div class="vote-voters">{{ getArtistVoterCount(row.artist.id) }} 人</div>
                </div>
              </template>
            </el-table-column>
            <el-table-column label="操作" width="120" fixed="right">
              <template #default="{ row }">
                <el-button 
                  size="small" 
                  type="danger" 
                  @click="removeArtist(row)"
                  v-if="userStore.hasPermission(ALL_PERMISSIONS.ACTIVITY_UPDATE)"
                >
                  移除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
        
        <div v-else class="no-artists">
          <el-empty description="暂无参与艺人">
            <el-button type="primary" @click="showAddArtistDialog = true">
              添加艺人
            </el-button>
          </el-empty>
        </div>
      </div>

      <!-- 投票统计图表 -->
      <div class="statistics-section">
        <h3>投票统计</h3>
        <div class="chart-container">
          <div ref="chartRef" style="width: 100%; height: 400px;"></div>
        </div>
      </div>
    </el-card>

    <!-- 编辑活动对话框 -->
    <el-dialog 
      v-model="showEditDialog" 
      title="编辑活动"
      width="600px"
    >
      <el-form 
        ref="editFormRef"
        :model="editForm" 
        :rules="formRules"
        label-width="100px"
      >
        <el-form-item label="活动名称" prop="name">
          <el-input v-model="editForm.name" placeholder="请输入活动名称" />
        </el-form-item>
        <el-form-item label="活动描述" prop="description">
          <el-input 
            v-model="editForm.description" 
            type="textarea" 
            :rows="3"
            placeholder="请输入活动描述"
          />
        </el-form-item>
        <el-form-item label="开始时间" prop="startTime">
          <el-date-picker
            v-model="editForm.startTime"
            type="datetime"
            placeholder="选择开始时间"
            format="YYYY-MM-DD HH:mm:ss"
            value-format="YYYY-MM-DD HH:mm:ss"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="结束时间" prop="endTime">
          <el-date-picker
            v-model="editForm.endTime"
            type="datetime"
            placeholder="选择结束时间"
            format="YYYY-MM-DD HH:mm:ss"
            value-format="YYYY-MM-DD HH:mm:ss"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select v-model="editForm.status" placeholder="选择状态">
            <el-option label="进行中" value="ACTIVE" />
            <el-option label="未开始" value="INACTIVE" />
            <el-option label="已完成" value="COMPLETED" />
            <el-option label="已取消" value="CANCELLED" />
          </el-select>
        </el-form-item>
        <el-form-item label="横幅图片" prop="bannerImage">
          <el-input v-model="editForm.bannerImage" placeholder="请输入图片URL" />
        </el-form-item>
        <el-form-item label="活动规则" prop="rules">
          <el-input 
            v-model="editForm.rules" 
            type="textarea" 
            :rows="4"
            placeholder="请输入活动规则"
          />
        </el-form-item>
        <el-form-item label="最大投票数" prop="maxVotesPerUser">
          <el-input-number 
            v-model="editForm.maxVotesPerUser" 
            :min="1" 
            :max="10"
            placeholder="每个用户最大投票数"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showEditDialog = false">取消</el-button>
        <el-button type="primary" @click="submitEdit" :loading="submitting">
          更新
        </el-button>
      </template>
    </el-dialog>

    <!-- 添加艺人对话框 -->
    <el-dialog 
      v-model="showAddArtistDialog" 
      title="添加艺人到活动"
      width="500px"
    >
      <el-form 
        ref="addArtistFormRef"
        :model="addArtistForm" 
        :rules="addArtistRules"
        label-width="100px"
      >
        <el-form-item label="选择艺人" prop="artistId">
          <el-select 
            v-model="addArtistForm.artistId" 
            placeholder="选择艺人"
            filterable
            style="width: 100%"
          >
            <el-option 
              v-for="artist in availableArtists" 
              :key="artist.id"
              :label="artist.name"
              :value="artist.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="排序顺序" prop="sortOrder">
          <el-input-number 
            v-model="addArtistForm.sortOrder" 
            :min="0" 
            placeholder="排序顺序"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showAddArtistDialog = false">取消</el-button>
        <el-button type="primary" @click="submitAddArtist" :loading="submitting">
          添加
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed, nextTick } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useUserStore } from '@/stores/user'
import { activityApi, artistApi } from '@/api'
import { ALL_PERMISSIONS } from '@/constants/permissions'
import type { Activity, Artist } from '@/types'
import { formatDateTime } from '@/utils/format'
import * as echarts from 'echarts'

const route = useRoute()
const router = useRouter()
const userStore = useUserStore()

// 响应式数据
const loading = ref(false)
const submitting = ref(false)
const showEditDialog = ref(false)
const showAddArtistDialog = ref(false)
const activity = ref<Activity | null>(null)
const availableArtists = ref<Artist[]>([])
const chartRef = ref()
const chartInstance = ref<echarts.ECharts>()
const voteStatistics = ref<any>(null)

// 表单引用
const formRef = ref()
const editFormRef = ref()
const addArtistFormRef = ref()

const editForm = reactive({
  id: 0,
  name: '',
  description: '',
  startTime: '',
  endTime: '',
  status: 'ACTIVE' as const,
  bannerImage: '',
  rules: '',
  maxVotesPerUser: 1
})

const addArtistForm = reactive({
  artistId: 0,
  sortOrder: 0
})

const formRules = {
  name: [
    { required: true, message: '请输入活动名称', trigger: 'blur' }
  ],
  startTime: [
    { required: true, message: '请选择开始时间', trigger: 'change' }
  ],
  endTime: [
    { required: true, message: '请选择结束时间', trigger: 'change' }
  ],
  maxVotesPerUser: [
    { required: true, message: '请设置最大投票数', trigger: 'blur' }
  ]
}

const addArtistRules = {
  artistId: [
    { required: true, message: '请选择艺人', trigger: 'change' }
  ]
}

// 计算属性
const activityId = computed(() => parseInt(route.params.id as string))

// 返回上一页
const goBack = () => {
  router.back()
}

// 获取活动详情
const fetchActivityDetail = async () => {
  loading.value = true
  try {
    const response = await activityApi.getDetail(activityId.value)
    activity.value = response.data
    Object.assign(editForm, response.data)
    
    // 获取投票统计
    await fetchVoteStatistics()
  } catch (error) {
    ElMessage.error('获取活动详情失败')
  } finally {
    loading.value = false
  }
}

// 获取投票统计
const fetchVoteStatistics = async () => {
  try {
    const response = await activityApi.getVoteStatistics(activityId.value)
    voteStatistics.value = response.data
  } catch (error) {
    console.error('获取投票统计失败:', error)
  }
}

// 获取艺人投票数
const getArtistVoteCount = (artistId: number) => {
  if (!voteStatistics.value?.artistStats) return 0
  const artistStat = voteStatistics.value.artistStats.find((stat: any) => stat.artist.id === artistId)
  return artistStat?.totalVotes || 0
}

// 获取艺人投票人数
const getArtistVoterCount = (artistId: number) => {
  if (!voteStatistics.value?.artistStats) return 0
  const artistStat = voteStatistics.value.artistStats.find((stat: any) => stat.artist.id === artistId)
  return artistStat?.uniqueVoters || 0
}

// 获取总投票数
const getTotalVotes = () => {
  if (!voteStatistics.value?.totalVotes) return 0
  return voteStatistics.value.totalVotes
}

// 获取总投票人数
const getTotalVoters = () => {
  if (!voteStatistics.value?.totalVoters) return 0
  return voteStatistics.value.totalVoters
}

// 更新艺人排序
const updateArtistOrder = async (artist: any) => {
  try {
    // 确保数据类型正确 - 必须是数字类型
    const artistId = Number(artist.artist.id)
    const sortOrder = Number(artist.sortOrder)
    
    // 验证数据类型
    if (isNaN(artistId) || isNaN(sortOrder)) {
      ElMessage.error('数据类型错误，请刷新页面重试')
      return
    }
    
    const requestData = {
      artists: [{
        artistId: artistId,
        sortOrder: sortOrder
      }]
    }
    
    await activityApi.updateArtistOrder(activityId.value, requestData)
    ElMessage.success('排序更新成功')
    fetchActivityDetail()
  } catch (error: any) {
    ElMessage.error(error.message || '排序更新失败')
    // 恢复原值
    fetchActivityDetail()
  }
}

// 获取可用艺人列表
const fetchAvailableArtists = async () => {
  try {
    const response = await artistApi.getList({ limit: 1000 })
    // 过滤掉已经在活动中的艺人
    const currentArtistIds = activity.value?.activityArtists?.map(aa => aa.artist.id) || []
    availableArtists.value = response.data.data.filter(artist => !currentArtistIds.includes(artist.id))
  } catch (error: any) {
    ElMessage.error('获取可用艺人列表失败')
  }
}

// 重置添加艺人表单
const resetAddArtistForm = () => {
  addArtistForm.artistId = 0
  addArtistForm.sortOrder = 0
  addArtistFormRef.value?.clearValidate()
}

// 提交添加艺人
const submitAddArtist = async () => {
  if (!addArtistFormRef.value) return
  
  try {
    await addArtistFormRef.value.validate()
    submitting.value = true
    
    await activityApi.addArtist({
      activityId: activityId.value,
      artistId: addArtistForm.artistId,
      sortOrder: addArtistForm.sortOrder
    })
    
    ElMessage.success('艺人添加成功')
    showAddArtistDialog.value = false
    fetchActivityDetail()
    resetAddArtistForm()
  } catch (error: any) {
    ElMessage.error(error.message || '艺人添加失败')
  } finally {
    submitting.value = false
  }
}

// 移除艺人
const removeArtist = async (artist: any) => {
  try {
    await ElMessageBox.confirm(
      `确定要从活动中移除艺人 "${artist.artist.name}" 吗？`,
      '确认移除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    await activityApi.removeArtist(activityId.value, artist.artist.id)
    ElMessage.success('艺人移除成功')
    fetchActivityDetail()
  } catch (error: any) {
    if (error !== 'cancel') {
      ElMessage.error(error.message || '艺人移除失败')
    }
  }
}

// 提交编辑
const submitEdit = async () => {
  try {
    submitting.value = true
    await activityApi.update(activityId.value, editForm)
    ElMessage.success('更新成功')
    showEditDialog.value = false
    fetchActivityDetail()
  } catch (error: any) {
    ElMessage.error(error.message || '更新失败')
  } finally {
    submitting.value = false
  }
}

// 获取状态类型
const getStatusType = (status: string) => {
  const statusMap: Record<string, string> = {
    ACTIVE: 'success',
    INACTIVE: 'info',
    COMPLETED: 'warning',
    CANCELLED: 'danger'
  }
  return statusMap[status] || 'info'
}

// 获取状态文本
const getStatusText = (status: string) => {
  const statusMap: Record<string, string> = {
    ACTIVE: '进行中',
    INACTIVE: '未开始',
    COMPLETED: '已完成',
    CANCELLED: '已取消'
  }
  return statusMap[status] || status
}

// 初始化图表
const initChart = () => {
  if (!chartRef.value || !voteStatistics.value?.artistStats) return
  
  chartInstance.value = echarts.init(chartRef.value)
  
  // 根据真实数据生成图表
  const artistNames = voteStatistics.value.artistStats.map((stat: any) => stat.artist.name)
  const voteData = voteStatistics.value.artistStats.map((stat: any) => stat.totalVotes)
  
  const option = {
    title: {
      text: '艺人投票统计',
      left: 'center'
    },
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow'
      },
      formatter: function(params: any) {
        const data = params[0]
        return `${data.name}<br/>投票数: ${data.value} 票`
      }
    },
    xAxis: {
      type: 'category',
      data: artistNames,
      axisLabel: {
        rotate: 45,
        interval: 0
      }
    },
    yAxis: {
      type: 'value',
      name: '投票数'
    },
    series: [
      {
        name: '投票数',
        type: 'bar',
        data: voteData,
        itemStyle: {
          color: '#409eff'
        },
        label: {
          show: true,
          position: 'top',
          formatter: '{c} 票'
        }
      }
    ]
  }
  
  chartInstance.value.setOption(option)
}

// 初始化
onMounted(async () => {
  await fetchActivityDetail()
  await fetchAvailableArtists()
  
  // 等待投票统计加载完成后再初始化图表
  nextTick(() => {
    if (voteStatistics.value?.artistStats) {
      initChart()
    }
  })
})
</script>

<style scoped>
.activity-detail-container {
  padding: 20px;
  max-width: 1400px;
  margin: 0 auto;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.header-left {
  display: flex;
  align-items: center;
  gap: 15px;
}

.page-title {
  margin: 0;
  font-size: 22px;
  color: #333;
  font-weight: 600;
}

.header-actions {
  display: flex;
  gap: 12px;
}

.breadcrumb {
  margin-bottom: 24px;
  font-size: 14px;
  color: #666;
  padding: 12px 16px;
  background: #f8f9fa;
  border-radius: 6px;
}

.activity-info-section {
  margin-bottom: 32px;
  padding: 24px;
  background: #f8f9fa;
  border-radius: 12px;
  border: 1px solid #e9ecef;
}

.activity-name {
  font-size: 24px;
  margin: 0 0 15px 0;
  color: #333;
}

.activity-description {
  font-size: 16px;
  color: #666;
  margin: 0 0 20px 0;
  line-height: 1.6;
}

.activity-meta {
  display: flex;
  flex-wrap: wrap;
  gap: 20px;
  margin-bottom: 20px;
}

.meta-item {
  font-size: 14px;
  color: #666;
}

.activity-rules h4 {
  margin: 0 0 10px 0;
  font-size: 16px;
  color: #333;
}

.activity-rules p {
  margin: 0;
  color: #666;
  line-height: 1.6;
}

.activity-banner img {
  width: 100%;
  border-radius: 8px;
  margin-bottom: 20px;
}

.activity-stats {
  display: flex;
  gap: 20px;
}

.stat-item {
  text-align: center;
  flex: 1;
}

.stat-number {
  font-size: 24px;
  font-weight: bold;
  color: #409eff;
}

.stat-label {
  font-size: 14px;
  color: #666;
  margin-top: 5px;
}

.artists-section {
  margin-bottom: 30px;
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding: 15px 20px;
  background: #f8f9fa;
  border-radius: 8px;
}

.section-header h3 {
  margin: 0;
  font-size: 18px;
  color: #333;
  font-weight: 600;
}

.artists-list {
  background: #fff;
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.artists-list :deep(.el-table) {
  border-radius: 8px;
  overflow: hidden;
}

.artists-list :deep(.el-table__header) {
  background: #f8f9fa;
}

.artists-list :deep(.el-table__header th) {
  background: #f8f9fa;
  color: #333;
  font-weight: 600;
  border-bottom: 1px solid #e4e7ed;
  padding: 12px 0;
}

.artists-list :deep(.el-table__row) {
  transition: background-color 0.3s ease;
}

.artists-list :deep(.el-table__row:hover) {
  background-color: #f5f7fa !important;
}

.artists-list :deep(.el-table__row td) {
  padding: 16px 0;
  border-bottom: 1px solid #f0f0f0;
}

.artists-list :deep(.el-table__row:last-child td) {
  border-bottom: none;
}

.artist-info {
  display: flex;
  align-items: center;
  gap: 15px;
  padding: 8px 0;
}

.artist-info :deep(.el-avatar) {
  border: 3px solid #fff;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  transition: all 0.3s ease;
}

.artist-info :deep(.el-avatar:hover) {
  transform: scale(1.05);
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.15);
}

.artist-details {
  flex: 1;
  min-width: 0;
}

.artist-details .artist-name {
  font-weight: 600;
  color: #333;
  margin-bottom: 8px;
  font-size: 16px;
  line-height: 1.4;
}

.artist-details .artist-description {
  font-size: 14px;
  color: #666;
  line-height: 1.5;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

.vote-stats {
  text-align: center;
  padding: 8px 0;
}

.vote-count {
  font-weight: 600;
  color: #67c23a;
  margin-bottom: 6px;
  font-size: 16px;
}

.vote-voters {
  font-size: 13px;
  color: #999;
  background: #f5f5f5;
  padding: 2px 8px;
  border-radius: 12px;
  display: inline-block;
}

.no-artists {
  text-align: center;
  padding: 60px 40px;
  background: #fafafa;
  border-radius: 8px;
  border: 2px dashed #ddd;
}

.no-artists .el-empty__description {
  color: #999;
  font-size: 16px;
  margin-top: 20px;
}

.statistics-section {
  margin-top: 30px;
}

.statistics-section h3 {
  margin: 0 0 20px 0;
  font-size: 18px;
  color: #333;
}

.chart-container {
  background: #f8f9fa;
  border-radius: 8px;
  padding: 20px;
}

.artists-list :deep(.el-input-number) {
  border-radius: 6px;
  border: 1px solid #dcdfe6;
  transition: all 0.3s ease;
}

.artists-list :deep(.el-input-number:hover) {
  border-color: #c0c4cc;
}

.artists-list :deep(.el-input-number.is-focus) {
  border-color: #409eff;
  box-shadow: 0 0 0 2px rgba(64, 158, 255, 0.2);
}

.artists-list :deep(.el-input-number .el-input__inner) {
  text-align: center;
  font-weight: 500;
  color: #333;
}

.artists-list :deep(.el-input-number .el-input-number__decrease),
.artists-list :deep(.el-input-number .el-input-number__increase) {
  border: none;
  background: #f5f7fa;
  color: #606266;
  transition: all 0.3s ease;
}

.artists-list :deep(.el-input-number .el-input-number__decrease:hover),
.artists-list :deep(.el-input-number .el-input-number__increase:hover) {
  background: #e4e7ed;
  color: #409eff;
}

.artists-list :deep(.el-button--danger) {
  border-radius: 6px;
  font-weight: 500;
  transition: all 0.3s ease;
  border: 1px solid #f56c6c;
  background: #fff;
  color: #f56c6c;
}

.artists-list :deep(.el-button--danger:hover) {
  background: #f56c6c;
  color: #fff;
  transform: translateY(-1px);
  box-shadow: 0 4px 12px rgba(245, 108, 108, 0.3);
}

.artists-list :deep(.el-button--danger:active) {
  transform: translateY(0);
  box-shadow: 0 2px 6px rgba(245, 108, 108, 0.3);
}
</style>
